package com.yc.navy.goods.websocket;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Component;

@Component
@ServerEndpoint("/websocket/{id}")
public class WebServerSocket {
	private static int onlineCount = 0;
	private static CopyOnWriteArraySet<WebServerSocket> webServerSocketset = new CopyOnWriteArraySet<WebServerSocket>();
	private Session session;
	private String aid;	 // 管理员
	
	@OnOpen
	public void OnOpen(Session session, @PathParam("id") String aid) {
		this.session = session;
		this.aid = aid;
		
		webServerSocketset.add(this);
		addOnLineCount();
		sendMessage("连接服务器成功....");
		System.out.println(LocalDateTime.now() + " 用户" + aid + " 连接上来了,当前在线用户人数:" + onlineCount + "...");
	}

	/**
	 * 发送消息的方法
	 * @param string
	 */
	public void sendMessage(String msg) {
		try {
			session.getBasicRemote().sendText(msg);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@OnClose
	public void Onclose() {
		webServerSocketset.remove(this);
		subOnLineCount();
		System.out.println(LocalDateTime.now() + " 用户" + aid + " 下线了,当前在线用户人数:" + onlineCount + "...");
	}
	
	@OnMessage
	public void OnMessage(Session session, String msg) {
		System.out.println(LocalDateTime.now() + "收到来自" + aid + " 用户发送的消息" + msg);
		for(WebServerSocket wss : webServerSocketset) {
			wss.sendMessage(msg);
		}
	}
	
	@OnError
	public void OnError(Session session, Throwable error) {
		new RuntimeException(error);
	}
	
	/**
	 * 根据用户aid获取登录信息
	 * @param aid
	 * @return
	 */
	public static WebServerSocket getWebServerSocket(String aid) {
		if(webServerSocketset.isEmpty()) {
			return null;
		}
		
		for(WebServerSocket wss : webServerSocketset) {
			if(aid.equals(wss.aid)) {
				return wss;
			}
		}
		return null;
	}
	
	private void subOnLineCount() {
		-- onlineCount;
		
	}

	private void addOnLineCount() {
		++ onlineCount;
	}
	
	public static int getOnLineCount() {
		return onlineCount;
	}
}
